home *** CD-ROM | disk | FTP | other *** search
- unit Str2Date;
-
- {
- Just a single function to extract
- a date value from a string.
-
- Why ? More flexible than Delphi's StrToDate.
-
- This is Freeware, you may use it without limitation.
- No warranty is provided, use it at your own risk.
- (I retain copyright on the original code)
- }
-
- interface
-
- function StrToDateNew(const sDateText: string; const bDayB4Month: boolean): TDateTime;
-
- implementation
-
- uses
- Windows,
- SysUtils;
-
- function StrToDateNew(const sDateText: string; const bDayB4Month: boolean): TDateTime;
- {
- Try to convert a string into a Date.
- The year must be a FOUR digit year.
-
- Used PChar's for performance, also step over all
- rubbish in in a single examination of the input string.
-
- Does not work on international MBCS :-(
- }
- var
- sWord: string;
- iValue: integer;
- bNumeric: boolean;
- PBeg, PNex: PChar;
- iInx, iDay, iMonth, iYear: integer;
- const
- ZeroToNine = ['0'..'9'];
- Separators = ['|', '/', '\', '-', '_', ',', '.', ' '];
- begin
-
- iDay := 0;
- iMonth := 0;
- iYear := 0;
-
- // Begin at the start of the input date string.
- PBeg := PChar(sDateText);
- // Skip all leading blanks and separators
- while PBeg^ in Separators do Inc(PBeg);
-
- // Empty input (string) - Empty output (31-12-1899)
- // Could raise an exception instead - up to you.
- if PBeg^ = #0 then
- begin
- Result := 1;
- exit;
- end;
-
- // Initialize
- sWord := '';
- iValue := 0;
- PNex := PBeg;
-
- repeat // Here we go ...
-
- // Have we got a number ?
- bNumeric := (PNex^ in ZeroToNine);
-
- if bNumeric then // Increment our integer value
- iValue := iValue * 10 + Ord(PNex^) - 48; // 48 = Ord('0')
-
- Inc(PNex); // Step forward to the next character ...
-
- if (PNex^ = #0 ) // End of String
- or (PNex^ in Separators) then
- begin // Process our current item
-
- if bNumeric then
- begin // Process iValue
-
- case iValue of
- 1899..3000:
- iYear := iValue;
- 13..31:
- iDay := iValue;
- 1..12:
- if iDay <> 0 then
- iMonth := iValue
- else
- if iMonth <> 0 then
- iDay := iValue
- else
- if bDayB4Month then
- iDay := iValue
- else
- iMonth := iValue;
- end; // Case iValue of
-
- iValue := 0; // Reset
- end
- else
- begin // Process sWord
-
- // If we don't already have the month
- // see if this word is a month name.
-
- if iMonth = 0 then
- begin
- SetString(sWord, PBeg, PNex - PBeg);
-
- sWord := UpperCase(sWord);
- if (PNex - PBeg) > 3 then SetLength(sWord, 3);
- iInx := Pos(sWord, 'JANFEBMARAPRMAYJUNJULAUGSEPOCTNOVDEC');
- if iInx > 0 then iMonth := Succ(iInx div 3);
-
- end; // if iMonth = 0 then
-
- sWord := ''; // Reset
- end; // Process sWord
-
- // Skip any blanks and separators
- while PNex^ in Separators do Inc(PNex);
-
- // Set start of next word or value item
- PBeg := PNex;
-
- end; // Processed our current item
-
- until PBeg^ = #0;
-
- Result := EncodeDate(iYear, iMonth, iDay);
- end;
-
- end.
-
-